package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 40. 组合总和 II
 * 回溯 + 剪枝
 *
 * @author fy
 * @date 2022/4/28 21:55
 */
public class Solution40 {

    private List<List<Integer>> res;
    private boolean[] isUsed;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        res = new ArrayList<>();
        isUsed = new boolean[candidates.length];
        // 对数组提前排序
        Arrays.sort(candidates);
        dfs(candidates, target, 0, new ArrayList<>());
        return res;

    }

    private void dfs(int[] candidates, int target, int index, List<Integer> preList) {
        if (target == 0) {
            res.add(new ArrayList<>(preList));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (target - candidate < 0) {
                break;
            }
            if (i > 0 && !isUsed[i] && !isUsed[i - 1] && candidates[i] == candidates[i - 1]) {
                continue;
            }
            target -= candidate;
            preList.add(candidate);
            isUsed[i] = true;
            dfs(candidates, target, i + 1, preList);
            isUsed[i] = false;
            preList.remove(preList.size() - 1);
            target += candidate;
        }
    }

}
